package foodmaterial.action;

import foodmaterial.config.ChoiceDataSource;
import foodmaterial.config.DataSourceContextHolder;
import foodmaterial.entity.*;
import foodmaterial.service.PermissionService;
import foodmaterial.utils.Constants;
import foodmaterial.utils.PasswordUtil;
import foodmaterial.utils.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo ;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/system")
@CrossOrigin(allowCredentials = "true")
public class PermissionAction extends BaseAction {

    @Autowired
    private PermissionService service ;

    @Autowired
    AuthenticationManager authenticationManager ;

    @Autowired
    RandomValidateCodeUtil randomValidateCodeUtil;

    @PostMapping("/userLogin")
    public void login(String username, String password) {
        /*System.out.println("---------------------" );
        // 1 创建UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(username, password) ;
        // 2 认证
        Authentication authentication = authenticationManager.authenticate(token);
        // 3 保存认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        SysUser userDetails = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser user = createSysUser(userDetails) ;
        System.out.println("---------------------" + userDetails);
        JsonResult jr = new JsonResult(true, "");
        jr.setData(user);
        return jr ;*/
    }

    @PostMapping("/addUser")
    @ChoiceDataSource
    public JsonResult<String> addUser(@RequestBody @Valid SysUser sysUser, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        SysUser userDetails = this.getSysUser();
        sysUser.setCreator(userDetails.getCreator());
        sysUser.setUpdateUser(userDetails.getCreator());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(sysUser.getCreateTime());
        sysUser.setDb(userDetails.getDb());
        sysUser.setPassword(PasswordUtil.encodePassword(Constants.DEFAULT_PASSWORD));//默认初始密码是123456
        sysUser.setLastLoginTime(sysUser.getCreateTime());
        String result = service.addUser(sysUser) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "新增用户成功") :
                JsonResultTool.get(jsonResult,false,result) ;
    }

    @PostMapping("/modifyUser")
    @ChoiceDataSource
    public JsonResult<String> modifyUser(@RequestBody @Valid SysUser sysUser, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        SysUser userDetails = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysUser.setUpdateUser(userDetails.getCreator());
        sysUser.setUpdateTime(new Date());
        String result = service.modifyUser(sysUser) ;
        return result == null ? JsonResultTool.get(jsonResult,true, "修改用户成功") :
                JsonResultTool.get(jsonResult,false,result)  ;
    }

    @PostMapping("/modifyPassword")
    @ChoiceDataSource
    public JsonResult<String> modifyPassword(@RequestBody SysUser sysUser) {
        String result = service.modifyPassword(sysUser) ;
        return StringUtils.isEmpty(result) ? new JsonResult(true, "修改密码成功") : new JsonResult(false,result) ;
    }

    @GetMapping("/queryUsers")
    @ChoiceDataSource
    public JsonResult<PageInfo<SysUser>> queryUsers(
            @RequestParam(value="pageNo",defaultValue = "1") Integer pageNo,
            @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(value="hasSupper", required=false) String hasSupper,
            @RequestParam(value="branchId", required=false) Long branchId,
            @RequestParam(value="name", required=false) String name) {
        if (pageNo <= 0) pageNo = 1 ;
        if (pageSize <= 0) pageSize = 10 ;
        PageHelper.startPage(pageNo,pageSize) ;
        List<SysUser> result = service.queryUsers(hasSupper,branchId,name);
        PageInfo<SysUser> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @GetMapping("/queryAdminUsers")
    public JsonResult<List<SysUser>> queryAdminUsers(
            @RequestParam(value="pageNo",defaultValue = "1") Integer pageNo,
            @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize) {
        if (pageNo <= 0) pageNo = 1 ;
        if (pageSize <= 0) pageSize = 10 ;
        PageHelper.startPage(pageNo,pageSize) ;
        List<SysUser> result = service.queryAdminUsers();
        PageInfo<SysUser> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @GetMapping("/queryUsersByUserType")
    @ChoiceDataSource
    public JsonResult<List<SysUser>> queryUsersByUserType(
            @RequestParam(value="userType") String userType) {
        List<SysUser> result = service.queryUsersByUserType(userType);
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @GetMapping("/choiceUsers")
    @ChoiceDataSource
    public JsonResult<List<Map<String, Object>>> choiceUsers(
            @RequestParam(value="userType") String userType) {
        List<Map<String, Object>> result = service.choiceUsers(userType);
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @GetMapping("/queryUserByAccount")
    @ChoiceDataSource
    public JsonResult<SysUser> queryUserByAccount(String account) {
        SysUser user = service.queryUserByAccount(account) ;
        return (user != null) ? new JsonResult(true,ResultCode.SUCCESS,user) :
        new JsonResult(true,"用户不存在");
    }

    @GetMapping("/queryRolesByUser")
    @ChoiceDataSource
    public JsonResult<List<SysRole>> queryRolesByUser(Long userId) {
        return new JsonResult(true,ResultCode.SUCCESS,service.queryRolesByUser(userId)) ;
    }

    /**
     * > 0  表示查询权限的时候，同时查询角色和权限对照信息，并自动勾上权限的checked属性
     * @param hasRole
     * @return
     */
    @GetMapping("/queryPermissions")
    @ChoiceDataSource
    public JsonResult<List<SysPermission>> queryPermissions(
            @RequestParam("hasRole") Long hasRole) {
        return new JsonResult(true,ResultCode.SUCCESS,service.queryPermissions(hasRole)) ;
    }

    @PostMapping("/addRole")
    @ChoiceDataSource
    public JsonResult<String> addRole(@RequestBody @Valid SysRole sysRole, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        String result = service.addRole(sysRole) ;
        return StringUtils.isEmpty(result) ? new JsonResult(true,"增加角色成功") : new JsonResult(false,result) ;
    }

    @PostMapping("/modifyRole")
    @ChoiceDataSource
    public JsonResult<String> modifyRole(@RequestBody SysRole sysRole) {
        String result = service.modifyRole(sysRole) ;
        return StringUtils.isEmpty(result) ? new JsonResult(true,"修改角色成功") : new JsonResult(false,result) ;
    }

    @PostMapping("/removeRole")
    @ChoiceDataSource
    public JsonResult<String> removeRole(@RequestBody SysRole role) {
        int result = service.removeRole(role.getId()) ;
        return result > 0 ? new JsonResult(true,"删除角色成功") : new JsonResult(false,"删除角色失败") ;
    }


    @GetMapping("/queryRoles")
    @ChoiceDataSource
    public JsonResult<PageInfo<SysRole>> queryRole(
            @RequestParam(value="pageNo",defaultValue = "1") Integer pageNo,
            @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize) {
        //否则如果有小于等于的0的数据，全部查询
        if (pageNo > 0 && pageSize > 0) {
            PageHelper.startPage(pageNo, pageSize);
        }
        List<SysRole> result = service.queryRole();
        PageInfo<SysRole> pageInfo = new PageInfo<>(result) ;
        return new JsonResult(true,ResultCode.SUCCESS,pageInfo)  ;
    }

    @PostMapping("/grant")
    @ChoiceDataSource
    public JsonResult<String> grant(@RequestBody Map<String,Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        List<String> roleList = (List<String>)params.get("roleList") ;
        int result = service.grant(userId,roleList) ;
        return result > 0 ? new JsonResult(true,"授权成功") : new JsonResult(false,"授权失败") ;
    }

    @PostMapping("/resetPassword")
    @ChoiceDataSource
    public JsonResult<String> resetPassword(@RequestBody SysUser user) {
        //系统管理员重置其它公司的密码，需要重新切换数据库
        if (!user.getDb().equals(DataSourceContextHolder.getDBType())) {
            DataSourceContextHolder.setDBType(user.getDb());
        }
        String result = service.resetPassword(user) ;
        return result == null ? new JsonResult(true,"重置成功") : new JsonResult(false,result) ;
    }

    @PostMapping("/modifySysParams")
    @ChoiceDataSource
    public JsonResult<String> modifySysParams(@RequestBody CompanySysParams companySysParams) {
        int result = service.modifySysParams(companySysParams) ;
        return result > 0 ? new JsonResult(true,"设置成功") : new JsonResult(false,"设置失败") ;
    }

    @GetMapping("/querySysParams")
    @ChoiceDataSource
    public JsonResult<List<CompanySysParams>> querySysParams() {
        List<CompanySysParams> data = service.querySysParams();
        return new JsonResult(true, ResultCode.SUCCESS,data) ;
    }

    @GetMapping("/querySysParamsByCode")
    @ChoiceDataSource
    public JsonResult<CompanySysParams> querySysParamsByCode(@RequestParam("code") String code) {
        return new JsonResult(true, ResultCode.SUCCESS,service.querySysParamsByCode(code)) ;
    }

    @GetMapping("/getCondimentWeek")
    @ChoiceDataSource
    public JsonResult<Integer> getCondimentWeek() {
        CompanySysParams csp = service.querySysParamsByCode("0001") ;
        return new JsonResult(true, ResultCode.SUCCESS,new Integer(csp.getParamValue())) ;
    }

    @GetMapping("/getStopWeek")
    @ChoiceDataSource
    public JsonResult<Integer> getStopWeek() {
        CompanySysParams csp = service.querySysParamsByCode("0002") ;
        return new JsonResult(true, ResultCode.SUCCESS,new Integer(csp.getParamValue())) ;
    }

    @GetMapping("/getNextWeekDateRange")
    public String getNextWeekDateRange() {
        return service.getNextWeekDateRange() ;
    }

    @GetMapping("/getSystemWeek")
    public String getSystemWeek() {
        return service.getSystemWeek() ;
    }

    @GetMapping("/verify")
    public void getVerify(HttpSession session,
                          HttpServletResponse response) {
        randomValidateCodeUtil.getRandCode(session,response);
    }

}
